package com.siteseat.crudeq.broker.netty;

import static org.jboss.netty.channel.Channels.pipeline;

import com.siteseat.crudeq.broker.transport.RequestHandlerRepository;
import com.siteseat.crudeq.broker.transport.BrokerSessionManager;
import com.siteseat.common.foundation.Component;
import com.siteseat.common.foundation.PropertyHelper;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;

/**
 * 
 *
 */
public class ServerPipelineFactory extends Component implements ChannelPipelineFactory {
  
  private BrokerSessionManager     sessionManager;

  private RequestHandlerRepository requestFactoryRepository;

  private BrokerSessionHandler     sessionHandler;

  private ExecutionHandler         decoder;

  /**
   * @param sessionManager
   */
  public ServerPipelineFactory( BrokerSessionManager sessionManager, RequestHandlerRepository requestFactoryRepository ) {
    this.sessionManager = sessionManager;
    this.requestFactoryRepository = requestFactoryRepository;
    this.sessionHandler = new BrokerSessionHandler( this.sessionManager );
    this.decoder = new ExecutionHandler( this.sessionManager, this.requestFactoryRepository );
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected void doInit() throws Exception {
    PropertyHelper.ensureInitialized( log, this.sessionManager, "sessionManager" );
    PropertyHelper.ensureInitialized( log, this.requestFactoryRepository, "requestFactoryRepository" );
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected void doDestroy() throws Exception {
    // do nothing so far
  }

  /**
   * Sets the enabled
   *
   * @param enabled the enabled to set
   */
  public void setEnabled( boolean enabled ) {
    this.requestFactoryRepository.setEnabled( enabled );
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public ChannelPipeline getPipeline() throws Exception {
    // Create a default pipeline implementation.
    ChannelPipeline pipeline = pipeline();

    pipeline.addLast( "conn", sessionHandler );

    // Add the text line codec combination first,
    pipeline.addLast( "codec", decoder );

    // and then business logic.
    // pipeline.addLast("handler", new TelnetServerHandler());

    return pipeline;
  }
}
